"use strict";

const { isObj } = require("@hjc-cli-dev/utils");
const pkgDir = require("pkg-dir").sync;
const npmInstall = require("npminstall");
const fsExtra = require("fs-extra");
const path = require("path");
const formatPath = require("@hjc-cli-dev/format-path");
const pathExistsSync = require("path-exists").sync;
const { getDefaultRegistry, getNpmLatestVersion } = require("@hjc-cli-dev/get-npm-info");
class Package {
    constructor(options) {
        if (!options) {
            throw Error("Package类的参数不能为空！");
        }
        if (!isObj) {
            throw Error("Package类的参数必须得是一个对象！");
        }
        // package的路径
        this.targetPath = options.targetPath;
        // package的存储路径
        this.storeDir = options.storeDir;
        // package的name
        this.packageName = options.packageName;
        // package的版本
        this.packageVersion = options.packageVersion;
        // package的前缀
        this.cacheFilePathPrefix = this.packageName.replace("/", "_");
    }
    async prepare() {
        // 当缓存目录不存在则创建缓存目录storeDir
        if (this.storeDir && !pathExistsSync(this.storeDir)) {
            fsExtra.mkdirpSync(this.storeDir);
        }
        if (this.packageVersion === "latest") {
            this.packageVersion = await getNpmLatestVersion(this.packageName);
        }
        // _@hjc-cli-dev_init@1.0.7@@hjc-cli-dev
    }

    get cacheFilePath() {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`);
    }
    latestCacheFilePath(packageVersion) {
        return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`);
    }
    // 判断当前package是否存在
    async exists() {
        // 判断缓存目录是否存在
        if (this.storeDir) {
            await this.prepare();
            return pathExistsSync(this.cacheFilePath);
        } else {
            return pathExistsSync(this.targetPath);
        }
    }
    // 安装package
    async install() {
        await this.prepare();
        return npmInstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(true),
            pkgs: [{ name: this.packageName, version: this.packageVersion }],
        });
    }
    // 更新package
    async update() {
        await this.prepare();
        // 1.获取最新的npm模块版本号
        const latestPackageVersion = await getNpmLatestVersion(this.packageName);
        // 2.查询最新的版本号对应的路径是否存在
        const latestFilePath = this.latestCacheFilePath(latestPackageVersion);
        // 3.如果不存在，则直接安装最新的版本
        if (!pathExistsSync(latestFilePath)) {
            console.log(this.targetPath, this.storeDir, latestPackageVersion, [
                { name: this.packageName, version: this.packageVersion },
            ]);
            await npmInstall({
                root: this.targetPath,
                storeDir: this.storeDir,
                registry: getDefaultRegistry(true),
                pkgs: [{ name: this.packageName, version: latestPackageVersion }],
            });
            this.packageVersion = latestPackageVersion;
        } else {
            this.packageVersion = latestPackageVersion;
        }
    }
    // 获取入口文件的路径
    getRootFilePath() {
        function _getRootFilePath(Path) {
            // 1.获取package.json所在的目录
            const dir = pkgDir(Path);

            if (dir) {
                // 2.读取package.json
                const pkgFile = require(path.resolve(dir, "package.json"));
                // 寻找main/lib
                if (pkgFile && pkgFile.main) {
                    return formatPath(path.resolve(dir, pkgFile.main));
                }
            }
            return null;
        }
        return this.storeDir ? _getRootFilePath(this.cacheFilePath) : _getRootFilePath(this.targetPath);
    }
}

module.exports = Package;
